import select
import socket

# 创建 socket 并监听
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 8000))
server_socket.listen(5)
server_socket.setblocking(False)  # 非阻塞
inputs = [server_socket]
print("Server listening on port 8000...")

while True:
    try:
        readable, _, _ = select.select(inputs, [], [])
        for s in readable:
            if s is server_socket:
                client_socket, addr = server_socket.accept()
                print("New connection from", addr)
                client_socket.setblocking(False)
                inputs.append(client_socket)
            else:
                try:
                    data = s.recv(1024)
                    if not data:
                        print("Connection closed by client")
                        inputs.remove(s)
                        s.close()
                    else:
                        print("Received:", data.decode(errors="ignore"))
                except ConnectionResetError:
                    print("Client forcibly closed the connection")
                    inputs.remove(s)
                    s.close()
    except KeyboardInterrupt:
        print("Shutting down server...")
        break
# 关闭所有 socket
for s in inputs:
    s.close()